package com.wugui.datatx.core.handler.impl;

import cn.hutool.core.util.ArrayUtil;
import com.wugui.datatx.core.biz.model.ReturnT;
import com.wugui.datatx.core.biz.model.TriggerParam;
import com.wugui.datatx.core.glue.GlueTypeEnum;
import com.wugui.datatx.core.handler.IJobHandler;
import com.wugui.datatx.core.log.JobFileAppender;
import com.wugui.datatx.core.log.JobLogger;
import com.wugui.datatx.core.util.ScriptUtil;
import com.wugui.datatx.core.util.ShardingUtil;
import java.io.File;
import lombok.Getter;

/** Created by xuxueli on 17/4/27. */
public class ScriptJobHandler extends IJobHandler {

  private final int jobId;
  @Getter private final long glueUpdateTime;
  private final String glueSource;
  private final GlueTypeEnum glueType;

  public ScriptJobHandler(
      int jobId, long glueUpdateTime, String glueSource, GlueTypeEnum glueType) {
    this.jobId = jobId;
    this.glueUpdateTime = glueUpdateTime;
    this.glueSource = glueSource;
    this.glueType = glueType;

    // clean old script file
    File glueSrcPath = new File(JobFileAppender.getGlueSrcPath());
    if (glueSrcPath.exists()) {
      File[] glueSrcFileList = glueSrcPath.listFiles();
      if (ArrayUtil.isNotEmpty(glueSrcFileList)) {
        for (File glueSrcFileItem : glueSrcFileList) {
          if (glueSrcFileItem.getName().startsWith(jobId + "_")) {
            glueSrcFileItem.delete();
          }
        }
      }
    }
  }

  @Override
  public ReturnT<String> execute(TriggerParam tgParam) throws Exception {
    if (!glueType.isScript()) {
      return new ReturnT<>(IJobHandler.FAIL.getCode(), "glueType[" + glueType + "] invalid.");
    }

    // cmd
    String cmd = glueType.getCmd();

    // make script file
    String scriptFileName =
        JobFileAppender.getGlueSrcPath()
            .concat(File.separator)
            .concat(String.valueOf(jobId))
            .concat("_")
            .concat(String.valueOf(glueUpdateTime))
            .concat(glueType.getSuffix());
    File scriptFile = new File(scriptFileName);
    if (!scriptFile.exists()) {
      ScriptUtil.markScriptFile(scriptFileName, glueSource);
    }

    // log file
    String logFileName = JobFileAppender.CONTEXT_HOLDER.get();

    // script params：0=param、1=分片序号、2=分片总数
    ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo();
    String[] scriptParams = new String[3];
    scriptParams[0] = tgParam.getExecutorParams();
    scriptParams[1] = String.valueOf(shardingVO.getIndex());
    scriptParams[2] = String.valueOf(shardingVO.getTotal());

    // invoke
    JobLogger.log("----------- script file:" + scriptFileName + " -----------");
    int exitValue =
        ScriptUtil.execToFile(
            cmd,
            scriptFileName,
            logFileName,
            tgParam.getLogId(),
            tgParam.getLogDateTime(),
            scriptParams);

    if (exitValue == 0) {
      return IJobHandler.SUCCESS;
    } else {
      return new ReturnT<>(
          IJobHandler.FAIL.getCode(), "script exit value(" + exitValue + ") is failed");
    }
  }
}
